<template>
	<view class="my-page">
		<view class="title">恩平市那吉镇急事“吉”办系统诉求单</view>
		<u-line></u-line>
		<view class="content">
			<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
			<u-form labelPosition="top" :model="model1" ref="form1">
				<u-form-item label="诉求类型" prop="type" labelWidth="70">
					<u-radio-group v-model="model1.type">
						<u-radio :customStyle="{marginRight: '16px'}" v-for="(item, index) in typelist" :key="index"
							:label="item.name" :name="item.name">
						</u-radio>
					</u-radio-group>
				</u-form-item>

				<u-form-item label="详细项目" prop="project" @click="showProject = true; hideKeyboard()" borderBottom
					labelWidth="70">
					<u-input v-model="model1.project" border="none" disabled disabledColor="#ffffff"
						placeholder="请选择详细项目">
					</u-input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-gap height="50"></u-gap>

				<u-form-item label="诉求描述" prop="intro" labelWidth="70">
					<u-textarea placeholder="请输入诉求内容" v-model="model1.intro" count></u-textarea>
				</u-form-item>

				<u-form-item label="诉求地址" prop="address" labelWidth="70" @click="chooseLocation">
					<u-input border="surround" placeholder="点击选择地址" v-model="model1.address" disabled suffixIcon="map-fill"
						suffixIconStyle="color: #909399">
					</u-input>
				</u-form-item>

				<u-form-item label="凭证上传" labelWidth="70">
					<u-upload :fileList="imageList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="8"></u-upload>
				</u-form-item>

				<u-form-item label="是否保密" prop="secrecy" borderBottom labelWidth="70">
					<u-radio-group v-model="model1.secrecy">
						<u-radio :customStyle="{marginRight: '16px'}" v-for="(item, index) in secrecyRadiovalue"
							:key="index" :label="item.name" :name="item.name">
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-gap height="50"></u-gap>

				<u-form-item label="姓名" prop="name" labelWidth="70"  required="true">
					<u-input border="surround" v-model="model1.name" placeholder="请输入联系人姓名">
					</u-input>
				</u-form-item>

				<u-form-item label="手机号码" prop="phone" labelWidth="70"  required="true">
					<u-input border="surround" v-model="model1.phone" placeholder="请输入联系人电话">
					</u-input>
				</u-form-item>

				<u-form-item label="详细地址" prop="detail_address" labelWidth="70">
					<u-input border="surround" v-model="model1.detail_address" placeholder="请输入详细地址">
					</u-input>
				</u-form-item>

			</u-form>
			<u-button type="error" text="提交" customStyle="margin-top: 50px" @click="submit"></u-button>
			<u-action-sheet :show="showProject" :actions="projectActions" title="请选择详细项目" @close="showProject = false"
				@select="projectSelect">
			</u-action-sheet>
		</view>
	</view>
</template>

<script>
	import * as Api from '@/api/appointment.js'
	export default {
		data() {
			return {
				id: null,
				imageList: [],
				model1: {
					name: '',
					address: '',
					phone: '',
					type: '建议',
					secrecy: '否',
					intro: '',
					project: '',
					detail_address: '',
					imagesId: []

				},

				typelist: [{
						name: '建议',
						disabled: false
					},
					{
						name: '咨询',
						disabled: false
					},
					{
						name: '反馈',
						disabled: false
					}, {
						name: '投诉',
						disabled: false
					}
				],
				secrecyRadiovalue: [{
						name: '是',
						disabled: false
					},
					{
						name: '否',
						disabled: true
					},
				],

				showProject: false,
				projectActions: [{
						name: '生活（临时救助）',
					},
					{
						name: '道路安全',
					},
					{
						name: '饮水（农村饮水安全）',
					},
					{
						name: '教育（控辍保学）',
					},
					{
						name: '饮水（农村饮水安全）',
					},
					{
						name: '就业（找工作、找培训 ）'
					},
					{
						name: '其它'
					}
				],

				rules: {
					type: {
						required: true,
						message: '请填写诉求类型',
						// blur和change事件触发检验
						trigger: ['blur', 'change'],
					},
					project: {
						required: true,
						message: '请填写详细项目',
						// blur和change事件触发检验
						trigger: ['blur', 'change'],
					},
					name: {
						required: true,
						message: '请填写姓名',
						// blur和change事件触发检验
						trigger: ['blur', 'change'],
					},
					phone: [{
						type: 'string',
						required: true,
						message: '联系方式将严格保密，仅用于满意度回访',
						trigger: ['blur', 'change']
					}, {
						// 此为同步验证，可以直接返回true或者false，如果是异步验证，稍微不同，见下方说明
						validator: (rule, value, callback) => {
							// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
							return uni.$u.test.mobile(value);
						},
						message: "请填写正确的手机号码",
						// 触发器可以同时用blur和change，二者之间用英文逗号隔开
						trigger: ["blur"],
					}],

				},
			}
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			console.log(option.id); //打印出上个页面传递的参数。
			this.id = option.id
			this.getDetail(option.id)
			
			wx.showShareMenu({
				withShareTicket: true,
				//设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
				menus: ["shareAppMessage", "shareTimeline"]
				// menus: ["shareAppMessage"]
			})
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules)

		},
		methods: {
			// 获取诉求详情
			getDetail(appointmentId) {
				Api.detail({
					params: {
						appointmentId
					}
				}).then(res => {
					console.log(res)
					this.model1 = res.detail
					this.model1.imagesId = []
					this.model1.deleteImagesId = []
					res.detail.images.forEach(e =>{
						this.imageList.push({size: e.file_size,thumb: e.external_url,type:'image',url: e.external_url})
						this.model1.imagesId.push(e.file_id)
					})
					
					delete res.detail.images
					this.model1 = res.detail
				}).catch(err => {
					uni.showModal({
						title: '请重新进入',
						showCancel: false,
						success: res => {
							if (res.confirm) {
								uni.redirectTo({
									url: '/pages/index/index'
								})
							}
						}
					})
				})
			},
			chooseLocation() {
				console.log('诉求地址')
				let self = this;
				uni.chooseLocation({
					success: (res) => {
						self.model1.address = res.address;

						console.log('位置名称：' + res.name);
						console.log('详细地址：' + res.address);
						console.log('纬度：' + res.latitude);
						console.log('经度：' + res.longitude);
					},
					fail: () => {
						// 如果用uni.chooseLocation没有获取到地理位置，则需要获取当前的授权信息，判断是否有地理授权信息

						uni.getSetting({
							success: (res) => {
								console.log(res);
								var status = res.authSetting;
								if (!status['scope.userLocation']) {
									// 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
									uni.showModal({
										title: "是否授权当前位置",
										content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
										success: (tip) => {
											if (tip.confirm) {
												// 如果用户同意授权地理信息，则打开授权设置页面，判断用户的操作
												uni.openSetting({
													success: (data) => {
														// 如果用户授权了地理信息在，则提示授权成功
														if (data
															.authSetting[
																'scope.userLocation'
															] === true
														) {
															uni.showToast({
																title: "授权成功",
																icon: "success",
																duration: 1000
															})
															// 授权成功后，然后再次chooseLocation获取信息
															uni.chooseLocation({
																success: (
																	res
																) => {
																	self.model1
																		.address =
																		res
																		.address;

																	console
																		.log(
																			'位置名称：' +
																			res
																			.name
																		);
																	console
																		.log(
																			'详细地址：' +
																			res
																			.address
																		);
																	console
																		.log(
																			'纬度：' +
																			res
																			.latitude
																		);
																	console
																		.log(
																			'经度：' +
																			res
																			.longitude
																		);
																}
															})
														} else {
															uni.showToast({
																title: "授权失败",
																icon: "none",
																duration: 1000
															})
														}
													}
												})
											}
										}
									})
								}
							},
							fail: (res) => {
								uni.showToast({
									title: "调用授权窗口失败",
									icon: "none",
									duration: 1000
								})
							}
						})
					}
				});
			},
			projectSelect(e) {
				this.model1.project = e.name
				this.$refs.form1.validateField('project')
			},
			submit() {
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.form1.validate().then(res => {
					uni.$u.toast('校验通过')
					console.log()
					// 验证成功，添加表单类型和预约类型参数
					const form = {
						...this.model1
					}
					delete form.create_time
					Api.edit({
						appointmentId: this.model1.appointment_id,
						form
					}).then(res => {
						console.log(res)
						// 提交成功，跳转到首页
						uni.showModal({
							title: '提交成功',
							showCancel: false,
							success: res => {
								if (res.confirm) {
									uni.redirectTo({
										url: '/pages/index/index'
									})
								}
							}
						});
					})

				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},

			hideKeyboard() {
				uni.hideKeyboard()
			},

			// 删除图片
			deletePic(event) {
				const imageId = this.model1.imagesId[event.index]
				Api.deleteFile({
					fileIds: [imageId]
				}).then(res => {
					this.model1.imagesId.splice(event.index, 1)
					this.imageList.splice(event.index, 1)
					this.model1.deleteImagesId.push(imageId)
				})
			},
			// 图片上传
			afterRead(e) {
				console.log(e)
				let lists = [].concat(e.file)
				this.imageList.push(...lists)
				console.log(this.imageList)
				lists.forEach(img => {
					const filePath = img.url
					Api.uploadImage({
						filePath,
						name: 'photo'
					}).then(res => {
						this.model1.imagesId.push(res.fileId)
					}).catch(err => {
						const imgIndex = this.imageList.findIndex((item) => item.url === filePath)
						this.imageList.splice(imgIndex, 1)
						uni.showToast({
							icon: 'none',
							title: '部分图片上传失败，请重试'
						})
					})
				})
				
			},
			
			onShareAppMessage() {
				return {
				  title: "恩平市那吉镇吉事吉办",
				  path: `/pages/index/index`
				 }
			},
			onShareTimeline(){
				return {
				  title: "恩平市那吉镇吉事吉办",
				  path: `/pages/index/index`
				 }
			}
		},
	}
</script>

<style scoped lang="scss">
	.my-page {
		margin: 0 20rpx;
		padding-top: 50rpx;
		padding-bottom: 50rpx;

		.title {
			padding: 25rpx 0;
			font-size: 40rpx;
			text-align: center;
		}

	}
</style>
